package com.sunyard.demo.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import redis.limiter.RedisTokenBucketRateLimiter;

/**
 * @author zyl
 * @description
 * @since 2025/8/22
 */
@Service
public class LoginService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    public void login(String username, String password, String ip) {
        // 创建IP级别的登录限流器
        RedisTokenBucketRateLimiter ipLimiter = new RedisTokenBucketRateLimiter(
                redisTemplate,
                "login:ip:" + ip,
                5,      // 突发5次登录尝试
                0.5     // 每2秒允许1次登录（0.5令牌/秒）
        );

        // 创建用户级别的登录限流器
        RedisTokenBucketRateLimiter userLimiter = new RedisTokenBucketRateLimiter(
                redisTemplate,
                "login:user:" + username,
                3,      // 突发3次
                0.3     // 约3秒1次
        );

        // 检查IP限流
        if (!ipLimiter.tryAcquire()) {
            throw new RuntimeException("IP登录尝试过于频繁，请稍后重试");
        }

        // 检查用户限流
        if (!userLimiter.tryAcquire()) {
            throw new RuntimeException("账号登录尝试过于频繁，请稍后重试");
        }

    }
}
